package com.yxq.sso.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 *
 * @author YXQ
 * @date 2021/11/29 16:37
 */
public class JsonUtil {
    private static ObjectMapper objectMapper = null;

    static {
        objectMapper = new ObjectMapper();
    }

    /**
     * 把对象转化成json字符串
     *
     * @param object 对象
     * @return 返回字符串
     */
    public static String objectToString(Object object){
        String jsonString = null;
        try {
            jsonString = objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            // TODO:工具类的异常也应该记录到系统日志中

        }
        return jsonString;
    }

    /**
     * 把jsonString转化为目标对象的方法
     *
     * @param jsonString json字符串
     * @param tClass 目标对象的Class类型
     * @param <T> 泛型
     * @return 擦除后的泛型对象
     */
    public static<T>  T stringToObject(String jsonString , Class<T> tClass){
        T t = null;
        try {
            t = objectMapper.readValue(jsonString, tClass);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            // TODO:工具类的异常也应该记录到系统日志中
        }
        return t;
    }
}
